import 'dart:io';

import 'package:dio/dio.dart';
import 'package:flutter/material.dart';
import 'package:flutter_easyloading/flutter_easyloading.dart';
import 'package:path_provider/path_provider.dart';
import 'package:home_framework/utils/http_util.dart';

import 'components/button_util.dart';

class FileDownlaodPage extends StatefulWidget {
  FileDownlaodPage({Key key}) : super(key: key);

  @override
  _FileDownlaodPageState createState() => _FileDownlaodPageState();
}

class _FileDownlaodPageState extends State<FileDownlaodPage> {
  String _downloadPath =
      'https://dl.google.com/chrome/mac/stable/GGRO/googlechrome.dmg';
  double _downloadRatio = 0.0;
  String _downloadIndicator = '0.00%';
  String _destPath;
  CancelToken _token;
  bool _downloading = false;

  @override
  void initState() {
    getTemporaryDirectory()
        .then((tempDir) => {_destPath = tempDir.path + 'googlechrome.dmg'});

    super.initState();
  }

  void _downloadFile() {
    _token = CancelToken();
    _downloading = true;
    HttpUtil.download(_downloadPath, _destPath, cancelToken: _token,
        onReceiveProgress: (int received, int total) {
      if (total != -1) {
        if (!_token.isCancelled) {
          setState(() {
            _downloadRatio = (received / total);
            if (_downloadRatio == 1) {
              _downloading = false;
            }
            _downloadIndicator =
                (_downloadRatio * 100).toStringAsFixed(2) + '%';
          });
        }
      } else {
        _downloading = false;
        EasyLoading.showError('无法获取文件大小，下载失败!');
      }
    });
  }

  void _cancelDownload() {
    if (_downloadRatio < 1.0) {
      _token.cancel();
      _downloading = false;
      setState(() {
        _downloadRatio = 0;
        _downloadIndicator = '0.00%';
      });
    }
  }

  void _deleteFile() {
    try {
      File downloadedFile = File(_destPath);
      if (downloadedFile.existsSync()) {
        downloadedFile.delete();
      } else {
        EasyLoading.showError('文件不存在');
      }
    } catch (e) {
      EasyLoading.showError(e.toString());
    }
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text('文件下载', style: Theme.of(context).textTheme.headline4),
        brightness: Brightness.dark,
      ),
      body: Center(
        child: Container(
          alignment: Alignment.center,
          margin: EdgeInsets.all(10),
          child: Column(
            mainAxisAlignment: MainAxisAlignment.center,
            children: [
              Row(
                children: [
                  Expanded(
                    child: ButtonUtil.primaryTextButton(
                      '下载文件',
                      () {
                        _downloadFile();
                      },
                      context,
                      height: 50,
                    ),
                  ),
                  TextButton(
                    child: Text('取消'),
                    onPressed: () {
                      _cancelDownload();
                    },
                  ),
                  TextButton(
                    child: Text(
                      '删除',
                      style: TextStyle(
                          color: !_downloading ? Colors.red : Colors.grey),
                    ),
                    onPressed: (!_downloading ? _deleteFile : null),
                    style: ButtonStyle(),
                  ),
                ],
              ),
              Row(children: [
                Expanded(
                  child: LinearProgressIndicator(
                    backgroundColor: Colors.grey[600],
                    value: _downloadRatio,
                  ),
                ),
                SizedBox(
                  width: 5,
                ),
                Text(
                  _downloadIndicator,
                  style: TextStyle(color: Colors.black, fontSize: 12.0),
                ),
              ]),
            ],
          ),
        ),
      ),
    );
  }
}
